﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace Event.EventBus
{
    public interface ISimpleEventBus
    {
        void Register<TEvent>(Action<TEvent> action);
        void Publish<TEvent>(TEvent @event);
    }

    public class SimpleEventBus
    {
        public static ConcurrentDictionary<Type,List<Action<object>>> Dictionary=new ConcurrentDictionary<Type, List<Action<object>>>();
 
        public void Register<TEvent>(Action<TEvent> action)
        {
            List<Action<object>> actionList;
            if (!Dictionary.TryGetValue(typeof (TEvent), out actionList))
            {
                actionList=new List<Action<object>>();
                Dictionary[typeof (TEvent)] = actionList;
            }
            actionList.Add(o=>action((TEvent)o));
        }

        public void Publish<TEvent>(TEvent @event)
        {
            List<Action<object>> actionList;
            if (Dictionary.TryGetValue(typeof (TEvent), out actionList))
            {
                foreach (var action in actionList)
                {
                    action(@event);
                }
            }
        }
    }
}
